#include "FriendModel.hpp"
#include "db.h"
#include <cassert>

bool FriendModel::insert(int userid, int friendid)
{
    char buffer[1024];
    int n = sprintf(buffer, "insert into Friend values(%d,%d)", userid, friendid);

    assert(n != 0);
    (void)n;

    MySQL sql;
    if (sql.connect())
    {
        mysql_set_character_set(sql.getConnection(), "utf8mb4");
        if (sql.update(buffer))
            return true;
    }

    return false;
}

std::vector<User> FriendModel::query(int userid)
{
    char buffer[1024];
    // 这里要用到一个联合查询，给一个userid，找到其所有好友的 id，name和state，
    // 再登录成功后就把这个信息推给上限的用户
    int n = sprintf(buffer, "select a.id,a.name,a.state from User as a inner join Friend as b where a.id = b.friend_id and user_id = %d", userid);

    assert(n != 0);
    (void)n;

    MySQL sql;
    std::vector<User> ret;
    if (sql.connect())
    {
        //设置连接字符集
        mysql_set_character_set(sql.getConnection(), "utf8mb4");

        MYSQL_RES *result = sql.query(buffer);

        if (result != nullptr)
        {
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(result)) != nullptr)
            {
                User user;
                user.setId(atoi(row[0]));
                user.setName(row[1]);
                user.setState(row[2]);

                ret.push_back(user);
            }
        }
        mysql_free_result(result);
        //这个ret是有意义的，这是一种防御性编程。 告诉读者不要往下读了
        return ret;
    }

    return ret;
}